package com.scalar.chiptrack.operations.dataentry.lotcorrection.actionCommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.operations.dataentry.dao.DataEntryDAO;
import com.scalar.chiptrack.operations.dataentry.lotcorrection.forms.LotCorrectionForm;
import com.scalar.chiptrack.operations.dataentry.lotcorrection.LotCorrection;
import com.scalar.chiptrack.operations.dataentry.lotcorrection.LotCorrectionHelper;

import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.commons.SessionKeys;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;
import java.sql.Date;

/**
 * User: Ganesh
 * Date: Dec 7, 2006
 * Time: 5:14:37 PM

 */
public class LotCorrectionSaveCommand extends ActionCommand
{
    private static final String ACTION_NAME = "/lotCorrection.do";

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception
    {
        LotCorrectionForm lotCorrectionForm = ( LotCorrectionForm ) form;
        LotCorrectionHelper lotCorrectionHelper= LotCorrectionHelper.getInstance();
        String action = request.getParameter("action");

        boolean success = false;

        HashMap errors = (HashMap)request.getAttribute(ERROR_MESSAGES);
        if ( errors == null )
        {
            errors = new HashMap();
            request.setAttribute(ERROR_MESSAGES, errors );
        }

        HashMap info = (HashMap)request.getAttribute(INFO_MESSAGES);
        if ( info == null )
        {
            info = new HashMap();
            request.setAttribute(INFO_MESSAGES, info );
        }

        HttpSession mSession = request.getSession();
        User user = (User) mSession.getAttribute(SessionKeys.USER_KEY);

        if (user == null)
        {
           mSession.setAttribute( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME );
           return ( mapping.findForward("login") );
        }
        else
        {
           if (user.isActionAllowed( Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY ))
           {
               request.setAttribute ( "showMessage", "FALSE" );
           }
           else
           {
               request.setAttribute ( "showMessage", "TRUE" );
           }
        }
        ArrayList correctionList = new ArrayList();
        LotCorrection lotCorrectionDetails = lotCorrectionForm.getLotCorrection();
        lotCorrectionDetails.setProcessType( lotCorrectionForm.getProcessType());
        lotCorrectionDetails.setProcessStepId(lotCorrectionForm.getProcessStepId());
        lotCorrectionDetails.setLocationId(lotCorrectionForm.getLocationId());
        lotCorrectionDetails.setLotId(lotCorrectionForm.getLotId());

        if (lotCorrectionDetails.getQuantityIn() != null && lotCorrectionDetails.getQuantityIn().trim().length() <= 0 )
        {
            lotCorrectionDetails.setQuantityIn(null);
        }

        if (lotCorrectionDetails.getWaferQtyIn() != null && lotCorrectionDetails.getWaferQtyIn().trim().length() <= 0)
        {
            lotCorrectionDetails.setWaferQtyIn(null);
        }
        if (lotCorrectionDetails.getDateOut() != null && lotCorrectionDetails.getDateOut().trim().length() <= 0 )
        {
            lotCorrectionDetails.setDateOut(null);
        }
        if ( lotCorrectionDetails.getWaferQtyOut() != null && lotCorrectionDetails.getWaferQtyOut().trim().length() <= 0 )
        {
            lotCorrectionDetails.setWaferQtyOut(null);
        }
        if ( lotCorrectionDetails.getQuantityOut() != null && lotCorrectionDetails.getQuantityOut().trim().length() <= 0 )
        {
            lotCorrectionDetails.setQuantityOut ( null );
        }

        if ( "Finished Goods".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "FG".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Assembly".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "FT".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "FPO".equalsIgnoreCase( lotCorrectionDetails.getProcessType() )  ||  "Bumping".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Sort".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Back Grind".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Class Store".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Tape".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Tape & Reel".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) )
        {

             if (!(lotCorrectionDetails.getLotNumber()).equalsIgnoreCase(lotCorrectionDetails.getVendorLotNumber().trim()))
             {
               lotCorrectionDetails.setLotNumber(lotCorrectionDetails.getVendorLotNumber());
             }
        }
        else if ("Fab".equalsIgnoreCase(lotCorrectionDetails.getProcessType()) || "FAB OPTION".equalsIgnoreCase(lotCorrectionDetails.getProcessType()) || "Bump Store".equalsIgnoreCase(lotCorrectionDetails.getProcessType()) || "Wafer Store".equalsIgnoreCase (lotCorrectionDetails.getProcessType()) || "Die Bank".equalsIgnoreCase(lotCorrectionDetails.getProcessType())  )
        {
             if (!(lotCorrectionDetails.getLotNumber()).equalsIgnoreCase(lotCorrectionDetails.getFabLotNumber().trim()))
             {
               lotCorrectionDetails.setLotNumber(lotCorrectionDetails.getFabLotNumber());
             }
        }

        correctionList.add ( lotCorrectionDetails );

        if( correctionList != null && correctionList.size() > 0 )
        {
            DBTransaction dbTransaction = null;
            try
            {
                if (!DataEntryDAO.checkDuplicateLots(null, lotCorrectionDetails))
                {
                    dbTransaction = DBTransaction.getInstance();
                    dbTransaction.begin();
                    DataEntryDAO.saveLotCorrectionLot( dbTransaction , correctionList );
                    dbTransaction.commit();
                    success = true;
                    info.put ( "Lot Correction Information Saved", null );
                }
                else
                {
                    if ( "Finished Goods".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "FG".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Assembly".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "FT".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "FPO".equalsIgnoreCase( lotCorrectionDetails.getProcessType() )  ||  "Bumping".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Sort".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Back Grind".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Class Store".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Tape".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) || "Tape & Reel".equalsIgnoreCase( lotCorrectionDetails.getProcessType() ) )
                    {
                        errors.put( "Another lot is existing with this Vendor lot number", null );
                    }
                    else if ("Fab".equalsIgnoreCase(lotCorrectionDetails.getProcessType()) || "Bump Store".equalsIgnoreCase(lotCorrectionDetails.getProcessType()) || "Wafer Store".equalsIgnoreCase (lotCorrectionDetails.getProcessType()) || "Die Bank".equalsIgnoreCase(lotCorrectionDetails.getProcessType())  )
                    {
                        errors.put( "Another lot is existing with this Fab lot number", null );
                    }
                    ArrayList lotCategoryList;
                    ArrayList processTypeList;
                    String processType = lotCorrectionForm.getProcessType();

                    ArrayList lotCorrectionPartNumbersLableValueBeans = new ArrayList();
                    ArrayList lotCorrectionLocationsLableValueBeans   = new ArrayList();
                    ArrayList lotCorrectionLotNumberLabelValueBeans   = new ArrayList();

                    try
                    {
                        processTypeList = lotCorrectionHelper.getProcessList();

                        lotCorrectionPartNumbersLableValueBeans= lotCorrectionHelper.getProductList(processType);

                        lotCorrectionLocationsLableValueBeans= lotCorrectionHelper.getLocationList(lotCorrectionForm.getProcessStepId());

                        lotCorrectionLotNumberLabelValueBeans = lotCorrectionHelper.getLotNumbersList(lotCorrectionForm.getProcessStepId(), lotCorrectionForm.getLocationId() );

                        LotCorrection lotCorrection = DataEntryDAO.getLotInfoByLotIdprocessType( lotCorrectionForm.getLotId(), processType );

                        if( lotCorrectionDetails.getDateIn() == null )
                        {
                            lotCorrectionDetails.setDateIn( StringUtils.formatDateToString( new Date(System.currentTimeMillis()), "MM/dd/yyyy"));
                        }

                        lotCategoryList = lotCorrectionHelper.getLotCategoryType();
                        lotCorrectionForm.setLotCorrection( lotCorrection  );

                        request.setAttribute ( "processList", processTypeList );
                        request.setAttribute ( "partNumbersList", lotCorrectionPartNumbersLableValueBeans );
                        request.setAttribute ( "locationList", lotCorrectionLocationsLableValueBeans );
                        request.setAttribute ( "lotNumberList", lotCorrectionLotNumberLabelValueBeans );
                        request.setAttribute ("lotCategoryList", lotCategoryList);

                        request.setAttribute("action", action);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    return mapping.findForward("lotCorrection");
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error storing the Lot Correction information", null );
            }
            finally
            {
                if ( dbTransaction != null )
                {
                    if ( !success )
                    {
                        dbTransaction.rollback();
                    }
                }
            }
        }
        ArrayList processList;

        lotCorrectionForm.setProcessType("0");
        lotCorrectionForm.setProcessStepId("0");
        lotCorrectionForm.setLocationId("0");
        lotCorrectionForm.setLotId("0");

        processList = lotCorrectionHelper.getProcessList();

        request.setAttribute("processList", processList);
        request.setAttribute("action", action);
        return mapping.findForward("lotCorrection");
    }

}
